#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: user.py
@time: 2025/7/23  10:31
# @describe:
"""
from flask import current_app
from flask_login import UserMixin
from datetime import date
import logging
from utils.data_utils import load_users, save_users


class User(UserMixin):
    def __init__(self, user_data):
        self.id = user_data['id']
        self.username = user_data['username']
        self.email = user_data['email']
        self.password = user_data['password']
        self.role = user_data.get('role', 'user')  # 'user', 'moderator', 'admin'
        self.data_add_records = user_data.get('data_add_records', {})
        self.pending_submissions = user_data.get('pending_submissions', 0)  # 待审核提交数

    def can_add_data(self):
        """检查用户是否可以添加数据"""
        if self.role == 'admin':
            return True
        max_daily = current_app.config['MAX_DAILY_ADDITIONS']
        return self.get_today_add_count() < max_daily

    def get_today_add_count(self):
        """获取今日已添加数据数量"""
        if self.role == 'admin':
            return 0

        today = date.today().isoformat()
        return self.data_add_records.get(today, 0)

    def record_data_add(self):
        """记录用户添加数据"""
        if self.role != 'admin':
            today = date.today().isoformat()
            current_count = self.data_add_records.get(today, 0)
            self.data_add_records[today] = current_count + 1
            self._save_user_data()

    def _save_user_data(self):
        """保存用户数据到文件"""
        try:
            users = load_users()
            for i, user in enumerate(users):
                if user['id'] == self.id:
                    users[i] = {
                        'id': self.id,
                        'username': self.username,
                        'email': self.email,
                        'password': self.password,
                        'role': self.role,
                        'data_add_records': self.data_add_records
                    }
                    break
            save_users(users)  # 直接调用导入的函数
            return True
        except Exception as e:
            logging.error(f"保存用户数据失败: {e}")
            return False